package cn.bone.stress.service;


import cn.bone.stress.bean.AccessRecord;
import cn.bone.stress.dao.AccessRecordDao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;


import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Created by superbone on 2017/3/29.
 */
@Service
public class ApiService {

    @Resource
    private AccessRecordDao accessRecordDao;
    private Logger logger = LoggerFactory.getLogger("业务方法");

    /**
     * 异步方法执行
     * 用来产生ListenableFuture对象供web层使用
     */
    @Async("businessAsync")
    public ListenableFuture<String> asyncExecute(){

        String result = execute();
        return new AsyncResult(result);
    }

    @Async("businessAsync")
    public ListenableFuture<String> error(){
        throw new RuntimeException("异常");
    }

    /**
     * 业务方法执行
     */
    public String execute(){

        logger.info("调用业务方法开始");

        //生成1000-4000的随机数
        Double random = Math.random() * 3000 + 1000;
        Long sleepTime = random.longValue();
        logger.info("随机休眠:"+sleepTime);
        try {
            TimeUnit.MILLISECONDS.sleep(sleepTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(random>3900){
            throw new RuntimeException(sleepTime+"");
        }

        AccessRecord record = new AccessRecord();
        record.setCreateTime(new Date());
        record.setFrom("test");
        record.setDeviceId(random+"");
        record.setMethod("test");
        record.setTimeConsume(sleepTime.intValue());
        accessRecordDao.save(record);

        logger.info("调用业务方法结束");

        return String.valueOf(sleepTime);
    }

}
